package org.restorator.controller;

import com.google.gson.Gson;
import org.restorator.entity.Table;
import org.restorator.service.TableService;
import org.restorator.service.impl.TableServiceImpl;
import org.restorator.utill.ControllerUtil;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.restorator.entity.dto.TableDto;

/**
 * Controller for work with REST style bulk requests on entity {@link org.restorator.entity.Table}.
 *
 * @author Snisar Bogdan. alltables
 */
@WebServlet(name = "tableAllController", urlPatterns = "/table")
public class TableAllController extends HttpServlet {



    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());

    private TableService tableService;

    @Override
    public void init() throws ServletException {
        super.init();
        tableService = new TableServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Table> tables = tableService.getAllTables();
            resp.setContentType("application/json");

            if(tables != null && !tables.isEmpty()) {
                logger.debug("get request. Fained  tables: {}", tables);

                ControllerUtil.printOk(resp.getWriter(), tableService.toDto(tables));;
            } else {
                ControllerUtil.printError(resp.getWriter());
            }
            
        } catch (Exception e) {
            logger.error("Exception in request processing: {}. \nStack trace: {}", e.getMessage(), e);
//            if exception - send 404 error
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
